<template>
  <div style="padding: 0 1em">
    <input type="text" v-model="itemText" @keydown.enter="createItem"><span>{{itemText}}</span>
    <ul v-if="todolist.length > 0">
      <li v-for="(item, index) in todolist">
        <span v-if="!item.completed" @click="handleCompleted(index)">{{ item.text }}</span>
      </li>
    </ul>
    <p v-else>暂无数据</p>
    <hr>
    {{ counter }}
    <hr>
    <h3>{{ counter1 }} <button @click="counter1++">修改</button></h3>
    <h3>
      ref(): {{ counter2 }}
      <button @click="counter2++">修改</button> |
      <button @click="setCounter2">修改</button>
    </h3>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  name: "DataComponent",
  // setup 执行在 beforeCreate 之前
  // 在 setup 内没法拿到 this
  // vue3 的学习，其实就是学习setup的语法
  setup() {
    // 在 setup 内可以声明状态使用 ref
    const counter1 = 10 // 不是响应式的
    const counter2 = ref(10) // ref 使变量加入的响应式系统中
    // console.log('setup')
    const setCounter2 = () => {
      console.log('counter2：', counter2.value) // 获取ref状态
      counter2.value++ // 修改ref状态
      console.log('counter2：', counter2.value) //
    }

    // todo
    const itemText = ref('')
    const todolist = ref([
      { id: 1, text: '吃饭', completed: false },
      { id: 2, text: '睡觉', completed: false },
      { id: 3, text: '打豆豆', completed: false },
    ])
    const createItem = () => {
      // console.log(itemText.value)
      todolist.value.push({
        id: Date.now(),
        text: itemText.value,
        completed: false
      })
      itemText.value = ''
      console.log(todolist.value) // vue3的响应式数据使用Proxy
    }

    const handleCompleted = (index) => {
      // todolist.value[index].completed = !todolist.value[index].completed
      // 删除
      todolist.value.splice(index, 1)
    }

    return { // 添加到setup的return内，才可以在视图中使用
      counter1,
      counter2,
      setCounter2,
      itemText,
      todolist,
      createItem,
      handleCompleted
    }
  },
  data() {
    return {
      counter: 1
    }
  },
  /*beforeCreate() {
    console.log('beforeCreate')
  }*/
}
</script>

<style scoped>

</style>